package com.deam.imsdk.net;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消息缓冲区
 */
public class MessagePullProcessor {
    public static final String MSG_END = "\r";//消息尾部
    private StringBuffer s = new StringBuffer();
    private MessageObserver messageObserver;
    private ExecutorService mCachedThreadPool = Executors.newCachedThreadPool();

    private void addRunable(Runnable runnable) {
        mCachedThreadPool.execute(runnable);
    }

    public synchronized void addMessage(String msg) {
        s.append(msg);
        doHandlerMessage();
    }

    private void doHandlerMessage() {
        addRunable(new Runnable() {
            @Override
            public void run() {
                synchronized (MessagePullProcessor.this) {
                    if (s.indexOf(MSG_END) != -1) {
                        String msg = s.substring(0, s.indexOf(MSG_END) + 1);
                        s.delete(0, s.indexOf(MSG_END) + 1);
                        JSONObject json = null;
                        try {
                            json = JSONObject.parseObject(msg);
                            if (messageObserver != null&&json!=null)
                                messageObserver.doHandleMessage(json);
                        } catch (JSONException e) {
                        }
                        doHandlerMessage();
                    }
                }
            }
        });
    }

    public void setMessageObserver(MessageObserver messageObserver) {
        this.messageObserver = messageObserver;
    }
}
